package com.freedom.sql.jdbc.handlers;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.sql.jdbc.netty.MyNioSocketChannel;
import com.freedom.sql.jdbc.pool.thread.ExecutorPool;
import com.freedom.sql.jdbc.pool.thread.MyRunnable;
import com.freedom.sql.jdbc.utils.LoggerUtils;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class MyLengthFieldBasedFrameDecoder extends LengthFieldBasedFrameDecoder {

	private static final Logger logger = LogManager.getLogger(MyLengthFieldBasedFrameDecoder.class);

	public MyLengthFieldBasedFrameDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength,
			int lengthAdjustment, int initialBytesToStrip) {
		super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
	}

	// 有些地方是需要改写方法的，进行精细控制
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		LoggerUtils.debug(logger, "***fixed length message in --- ");
		LoggerUtils.debug(logger, "ctx --- " + ctx.getClass());
		// 所有的完整报文，都直接抛到线程池里运行
		ExecutorPool.getInstance().execute(new MyRunnable(ctx, (MyNioSocketChannel) (ctx.channel()), msg));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		LoggerUtils.error(logger, cause.toString());
		ctx.close();
	}

}
